package com.example.springbootwxminiappintegrat.controller;

import com.example.springbootwxminiappintegrat.bean.NotifyBody;
import com.example.springbootwxminiappintegrat.bean.WeChatDecryptNotifyContent;
import com.example.springbootwxminiappintegrat.bean.WeChatNotify;
import com.example.springbootwxminiappintegrat.util.pay.wx.WeChatAesUtil;
import com.google.gson.Gson;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author qurenneng
 * 回调方法处理:
 */
@Slf4j
@RestController
@RequestMapping("/miniapp/notify")
public class MiniappNotifyController {

    private final WeChatAesUtil weChatAesUtil;

    public MiniappNotifyController(WeChatAesUtil weChatAesUtil) {
        this.weChatAesUtil = weChatAesUtil;
    }

    @PostMapping("weChat")
    public String acceptNotify(@RequestBody WeChatNotify notify) throws Exception {
        log.info("接收到JSAPI支付通知 {}", notify.toString());
        Gson gson = new Gson();
        String decrypt = weChatAesUtil.decryptToString(notify.getResource()
                        .getAssociated_data()
                        .getBytes(StandardCharsets.UTF_8),
                notify.getResource().getNonce().getBytes(StandardCharsets.UTF_8),
                notify.getResource().getCiphertext());
        //获取微信通知数据，接下来，自己去做业务处理：
        WeChatDecryptNotifyContent content = gson
                .fromJson(decrypt, WeChatDecryptNotifyContent.class);

        return gson.toJson(new NotifyBody("SUCCESS", "成功"));
    }

}
